// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

#include <stdexcept>

#include "PackageExpression.h"

using namespace CangjieMigrator;

PackageExpression::PackageExpression(const std::string &expression)
{
    const auto pos = expression.find_last_of('.');
    if (pos == std::string::npos || pos == 0 || pos == expression.length() - 1) {
        throw std::invalid_argument(
            "Invalid expression \"" + expression + "\". Cannot find '.' or it is at an invalid position.");
    }

    package = expression.substr(0, pos);
    identifier = expression.substr(pos + 1);
    if (package.empty() || identifier.empty()) {
        throw std::invalid_argument(
            "Invalid expression \"" + expression + "\". Package or identifier cannot be empty.");
    }
}

PackageExpression::PackageExpression(std::string package, std::string identifier)
    : package(std::move(package)), identifier(std::move(identifier))
{}

bool PackageExpression::IsInclude(const PackageExpression &other) const
{
    if (package != other.package) {
        return false;
    }
    if (identifier != other.identifier && identifier != "*") {
        return false;
    }
    return true;
}

std::string PackageExpression::ToString() const
{
    return package + "." + identifier;
}
